/**
 * 
 */
package cn.ivicar.app.controller;

import org.codehaus.plexus.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.inject.Inject;

import cn.com.carsmart.exception.BadRequestException;
import cn.com.carsmart.exception.CarsmartException;
import cn.com.carsmart.ws.model.CustomerVehicle;
import cn.ivicar.app.controller.service.CustomerVehicleService;
import cn.ivicar.app.controller.service.RelationService;

/**
 * 管理sim卡和车辆连接
 * @author liurunbin 2017年6月9日 cn.ivicar.app.controller
 */
public class RelationController {

	private static transient final Logger LOGGER = LoggerFactory.getLogger(RelationController.class);

	@Inject
	private CustomerVehicleService cvService;
	@Inject
	private RelationService relationService;
    /*
     获取Iccid
     */
	public String getIccid(Long customerId, Long vehicleId) throws CarsmartException {

		if (vehicleId == null || customerId == null) {
			throw new BadRequestException("400", "请求参数不能为空!");
		}
		CustomerVehicle cv = cvService.get(customerId, vehicleId);
		if (cv == null) {
			LOGGER.info(String.format("用户[customerId = %s]尚未关联车辆[vehicleId = %s]", customerId, vehicleId));
			throw new BadRequestException("400", "当前用户尚未关联这辆车");
		}

		if (!cv.getOwner()) {
			LOGGER.info(
					String.format("用户[customerId = %s]非车辆owner[vehicleId = %s]，无权获取对应的iccid", customerId, vehicleId));
			throw new BadRequestException("400", "无权访问");
		}

		return relationService.getIccid(vehicleId);

	}
	
    /*
    验证sim卡和车辆是否关联
     */
	public void validate(Long customerId, String iccid) throws CarsmartException {

		if(customerId == null){
			throw new BadRequestException("400", "请指定customerId!");
		}
		
		if(StringUtils.isBlank(iccid)){
			throw new BadRequestException("400", "请指定iccid!");
		}
		
		Long vehicleId = relationService.getVehicleId(iccid);
		if (vehicleId == null) {
			LOGGER.warn(String.format("SIM卡[iccid=%s]尚未关联车辆!", iccid));
			throw new BadRequestException("400", "SIM卡尚未关联车辆!");
		}

		CustomerVehicle ownercv = cvService.get(customerId, vehicleId);
		if (ownercv == null) {
			LOGGER.info(String.format("用户[customerId = %s]尚未关联车辆[vehicleId = %s]", customerId, vehicleId));
			throw new BadRequestException("400", "当前用户尚未关联此SIM卡");
		}

	}

}
